package util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * Created by jeff.zhou on 2017/9/25.
 * 网络服务工具类
 */
public class IntelUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(IntelUtil.class);

    private static String serverIp = StringUtils.EMPTY;

    static {
        final Properties props = System.getProperties();
        final String osName = props.getProperty("os.name");

        try {
            InetAddress inter;
            //根据当前系统获取IP
            if (osName.contains("Window")) {
                inter = getWinLocalIp();
            } else {
                inter = getUnixLocalIp();
            }

            if (null == inter) {
                throw new UnknownHostException("主机的ip地址未知!");
            }

            serverIp = inter.getHostAddress();
        } catch (Exception e) {
            LOGGER.error("获取本机ip错误:", e);
            serverIp = null;
        }

    }

    //获取windows系统下的IP
    private static InetAddress getWinLocalIp() throws UnknownHostException {
        return InetAddress.getLocalHost();
    }
    //获取linux系统下的IP
    private static InetAddress getUnixLocalIp() throws SocketException {
        final Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;

        while (true) {
            NetworkInterface ni;
            String name;
            do {
                do {
                    if (!netInterfaces.hasMoreElements()) {
                        return null;
                    }

                    ni = (NetworkInterface) netInterfaces.nextElement();
                    name = ni.getName();
                } while (name.contains("docker"));
            } while (name.contains("lo"));

            Enumeration ips = ni.getInetAddresses();

            while (ips.hasMoreElements()) {
                ip = (InetAddress) ips.nextElement();
                if (!ip.isLoopbackAddress() && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
                    return ip;
                }
            }
        }
    }

    public static String getServerIp() {
        return serverIp;
    }
}
